#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from dws.commons.common import log
from dws.commons.function_tool import log_start
from dws.resource.dws_common import DwsCommon

START_FLAG = "List of databases"
MIN_SPLIT_COUNT = 3
DN_NAME_POS = 0
SYS_DATABASE = ["template0", "template1"]


class DwsDatabase:

    def __init__(self, user_name, env_file, pid=""):
        self._original_database_lines = []
        self._user_name = user_name
        self._env_file = env_file
        self._pid = pid
        self._query_success = False
        self._exec_query_database()

    def is_db_exists(self, db_name):
        if not self._query_success:
            log.error(f"Query success ,  PID: {self._pid}.")
            return False
        return db_name in self.get_all_databases().split(",")

    @log_start()
    def get_all_databases(self):
        """
        从字符串中筛选出所有的数据库名称
        """
        if not self._query_success:
            log.error(f"Query success flag is false, PID: {self._pid}.")
            return ""
        start_index = -1
        end_index = len(self._original_database_lines) - 1
        for index, cur_line in enumerate(self._original_database_lines):
            if START_FLAG in cur_line:
                start_index = index + 3
                break
        if start_index == -1:
            log.error(f"Cannot find start flage in query database result, PID: {self._pid}.")
            return ""

        databases = []
        for index in range(start_index, end_index):
            temp_list = self._original_database_lines[index].split("|")
            if len(temp_list) < MIN_SPLIT_COUNT:
                continue
            if temp_list[DN_NAME_POS].strip() and temp_list[DN_NAME_POS + 1].strip():
                db_name = temp_list[DN_NAME_POS].strip()
                # 排除系统数据库
                if db_name not in SYS_DATABASE:
                    databases.append(db_name)

        return ",".join(databases)

    def _exec_query_database(self):
        """
        查找所有数据库
        """
        common_obj = DwsCommon(self._user_name, self._env_file, self._pid)
        # 登录postgres数据库，并查询所有数据库
        self._query_success, self._original_database_lines = common_obj.exec_gaussdb_sql_cmd("postgres", "\l")
        if not self._query_success:
            log.error(f"Query all databases faild,  PID: {self._pid}.")
            return False

        return True
